package edu.xaut.bookingsys.utils;

import cn.dev33.satoken.secure.SaSecureUtil;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;

public class SecretUtils {
    // teacherId -> privateKey
    private static HashMap<String, KeyPair> rsaHashMap = new HashMap<>();
    final static String sqlAESKey = "fjfkdlfajiklfdjakfjdakfjio901    orufasfdasfaso0rfiwajdfa";

    /**
     * @param teacherId 老师id
     * @return 公钥
     * @throws Exception
     */
    public static String genRsaPair(String teacherId) throws Exception {
        if (!rsaHashMap.containsKey(teacherId)) {
            var pair = RSAUtils.getKeyPair();
            rsaHashMap.put(teacherId, pair);
        }
        return RSAUtils.getPublicKey(rsaHashMap.get(teacherId));
    }

    public static boolean checkRSAWithDESSql(String teacherId, String vuePwd, String sqlPwd) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
        return  decryptAESInSql(sqlPwd).equals(decryptRSAById(teacherId,vuePwd));
    }
    private static String decryptRSAById(String teacherId, String vuePwd) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
        if (!rsaHashMap.containsKey(teacherId))
            return null;
        return new String(RSAUtils.privateDecrypt(Base64.getDecoder().decode(vuePwd), rsaHashMap.get(teacherId).getPrivate()));
    }
    public static String encryptAESInSql(String pwd) {
        return SaSecureUtil.aesEncrypt(sqlAESKey, pwd);
    }
    public static String decryptAESInSql(String pwd){
        return SaSecureUtil.aesDecrypt(sqlAESKey,pwd);
    }
    public static void delRSaPair(String teacherId)
    {
        rsaHashMap.remove(teacherId);
    }
}
